package cn.txzhang.bookstores.modular.business.service;

import cn.stylefeng.roses.kernel.db.api.factory.PageFactory;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.txzhang.bookstores.modular.business.entity.BookEntity;
import cn.txzhang.bookstores.modular.business.mapper.BookMapper;
import cn.txzhang.bookstores.modular.business.vo.BookAddDTO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class BookService extends ServiceImpl<BookMapper, BookEntity> {

    public void saveOrUpdate(BookAddDTO data) {
        Long id = data.getId();
        if (id == null) {
            BookEntity entity = new BookEntity();
            BeanUtils.copyProperties(data, entity);
            entity.setCreateTime(LocalDateTime.now());
            save(entity);
            return;
        }
        BookEntity entity = getById(id);
        BeanUtils.copyProperties(data, entity, "id");
        updateById(entity);
    }

    public PageResult<BookEntity> list(String bookName) {
        LambdaQueryWrapper<BookEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.like(StringUtils.isNotBlank(bookName), BookEntity::getBookName, bookName);
        Page<BookEntity> page = this.page(PageFactory.defaultPage(), wrapper);
        return PageResultFactory.createPageResult(page);
    }
}
